import Menu from '@/config/menu.js'
import crypto from '@/core/crypto.js'
import store from '@/store'
import Global from '@/config/global'
import qs from 'qs'
import Vue from 'vue'
import Session from '@/core/session'

/**
 * 获取历史的 nav list
 * @param {*} list
 */
export const getHistoryList = list => {
  return JSON.parse(JSON.stringify(list))
}

/**
 * 获取初始的list
 * @param {*} list
 */
export const getInitList = list => {
  // 传入的 list 是初始的 list 只有一个站点首页的菜单
  // 如果有需要从历史的导航相中获取list可以在这里修改
  return JSON.parse(JSON.stringify(list))
}

/**
 * 判断 list 当中是否存在，如果存在则直接返回true，不存在返回false
 * @param {*} list
 * @param {*} fullPath
 */
export const pathIsExistInNavList = (list, fullPath) => {
  for (let i in list) {
    let na = list[i]
    if (fullPath === na.path) {
      return true
    }
  }
  return false
}

/**
 * 通过menu 中其中一个的数据获取其对应的 fullPath 的name
 * @param {*} menu
 * @param {*} fullPath
 */
export const getNavNameByPath = (menu, fullPath) => {
  if (menu.path === fullPath) {
    return menu.name
  }
  if (!menu.children || menu.children.length < 1) {
    console.error(fullPath + ' 未定义', menu)
    return '未定义'
  }
  for (let i in menu.children) {
    let children = menu.children[i]
    if (fullPath.indexOf(children.path) === 0) {
      return children.name
    }
  }
  console.error(fullPath + ' 未定义', menu)
  return '未定义'
}

/**
 * 通过fullPath 在Menu 中找到对应数据的name
 * @param {*} fullPath
 */
export const getMenuItemByPath = fullPath => {
  for (let i in Menu) {
    let menu = Menu[i]
    if (menu.path === fullPath) {
      return menu
    }
    if (menu.children && menu.children.length > 0) {
      for (let i in menu.children) {
        let children = menu.children[i]
        if (fullPath.indexOf(children.path) > -1) {
          return menu
        }
      }
    }
  }
  console.error(fullPath + ' 未定义', Menu)
  return '未定义'
}

/**
 * 通过Menu配置获取对应index的menu
 * @param {*} menus
 * @param {*} index
 */
export const getMenuItemByIndex = index => {
  for (let i in Menu) {
    let menu = Menu[i]
    if (index === menu.index) {
      return menu
    }
  }
  console.error('index: ' + index + ' 未定义', Menu)
  return false
}

/**
 * 从 list 中删除path 对于 path 的数据后生成新的list并返回
 * @param {*} list
 * @param {*} path
 */
export const deletePathInList = (list, path) => {
  let result = []
  for (let i in list) {
    let item = list[i]
    if (item.path === path) {
      continue
    }
    result.push(item)
  }
  return JSON.parse(JSON.stringify(result))
}

/**
 * 通过要删除的 path，在 list 中找出另外一个用在当前的path
 * @param {*} list
 * @param {*} path
 */
export const findOtherCurrentPath = (list, path) => {
  let length = list.length
  if (length <= 2) {
    // 删除后只能是后台首页
    return '/backend/user'
  }
  // 找出当前的path所在的索引
  let index
  for (let i in list) {
    let item = list[i]
    if (item.path === path) {
      index = parseInt(i)
      break
    }
  }
  index = index + 1
  if (index > length - 1) {
    index = length - 2
  }
  return list[index].path
}

/**
 * 通过 id 到 Menu 中查找对应的的path
 * @param {*} id
 */
export const getChildrenById = id => {
  for (let i in Menu) {
    let menu = Menu[i]
    if (menu.children && menu.children.length > 0) {
      for (let i in menu.children) {
        let children = menu.children[i]
        if (children.id === id) {
          return children
        }
      }
    }
  }
  return false
}

/**
 * 通过 sid 制作 系统分类的uri
 * @param {*} sid
 */
export const getSystemCategoryPatjBySid = sid => {
  let children = getChildrenById('UserSystemCategory')
  if (!children) {
    return false
  }
  return children.path + '?sid=' + sid
}

/**
 * 通过 sid 制作 下载系统属性的uri
 * @param {*} sid
 */
export const getSystemDownloadAttrBySid = sid => {
  let children = getChildrenById('UserSystemDownloadAttr')
  if (!children) {
    return false
  }
  return children.path + '?sid=' + sid
}

/**
 * 通过 sid 制作 信息系统属性的uri
 * @param {*} sid
 */
export const getSystemInformationAttrBySid = sid => {
  let children = getChildrenById('UserSystemInformationAttr')
  if (!children) {
    return false
  }
  return children.path + '?sid=' + sid
}

/**
 * 通过 sid 制作 产品表格系统属性的uri
 * @param {*} sid
 */
export const getSystemPdtableAttrBySid = sid => {
  let children = getChildrenById('UserSystemPdtableAttr')
  if (!children) {
    return false
  }
  return children.path + '?sid=' + sid
}
/**
 * 获取系统列表页编辑地址
 * @param {*} item
 */
export const getSystemListPathByItem = item => {
  let children
  if (item.systemType.id === 1 || item.systemType.id === 2) {
    children = getChildrenById('UserSystemArticleList')
    if (!children) {
      return false
    }
  } else if (item.systemType.id === 3 || item.systemType.id === 4) {
    children = getChildrenById('UserSystemProductList')
    if (!children) {
      return false
    }
  } else if (item.systemType.id === 5) {
    children = getChildrenById('UserSystemDownloadList')
    if (!children) {
      return false
    }
  } else if (item.systemType.id === 6) {
    children = getChildrenById('UserSystemFaqList')
    if (!children) {
      return false
    }
  } else if (item.systemType.id === 7) {
    children = getChildrenById('UserSystemInformationList')
    if (!children) {
      return false
    }
  } else if (item.systemType.id === 8) {
    children = getChildrenById('UserSystemPdtableList')
    if (!children) {
      return false
    }
  }
  if (!children) {
    return false
  }
  return children.path + '?sid=' + item.id
}

/**
 * 通过 sid 制作 产品系统系统回收站的uri
 * @param {*} sid
 */
export const getSystemProductRefuseBySid = sid => {
  let children = getChildrenById('UserSystemProductRefuse')
  if (!children) {
    return false
  }
  return children.path + '?sid=' + sid
}

/**
 * 通过 sid 制作 文章系统系统回收站的uri
 * @param {*} sid
 */
export const getSystemArticleRefuseBySid = sid => {
  let children = getChildrenById('UserSystemArticleRefuse')
  if (!children) {
    return false
  }
  return children.path + '?sid=' + sid
}

/**
 * 通过 sid 制作 Faq系统系统回收站的uri
 * @param {*} sid
 */
export const getSystemFaqRefuseBySid = sid => {
  let children = getChildrenById('UserSystemFaqRefuse')
  if (!children) {
    return false
  }
  return children.path + '?sid=' + sid
}

/**
 * 通过 sid 制作 下载系统系统回收站的uri
 * @param {*} sid
 */
export const getSystemDownloadRefuseBySid = sid => {
  let children = getChildrenById('UserSystemDownloadRefuse')
  if (!children) {
    return false
  }
  return children.path + '?sid=' + sid
}

/**
 * 通过 sid 制作 信息系统系统回收站的uri
 * @param {*} sid
 */
export const getSystemInformationRefuseBySid = sid => {
  let children = getChildrenById('UserSystemInformationRefuse')
  if (!children) {
    return false
  }
  return children.path + '?sid=' + sid
}

/**
 * 通过 sid 制作 产品表格系统系统回收站的uri
 * @param {*} sid
 */
export const getSystemPdtableRefuseBySid = sid => {
  let children = getChildrenById('UserSystemPdtableRefuse')
  if (!children) {
    return false
  }
  return children.path + '?sid=' + sid
}

/**
 * 获取提交表单信息列表页编辑地址
 * @param {*} item
 */
export const getFormListPathByItem = item => {
  let cItem = null
  for (let i in Menu) {
    let menu = Menu[i]
    if (menu.children && menu.children.length > 0) {
      for (let i in menu.children) {
        let children = menu.children[i]
        if (children.id === 'UserFormInfo') {
          cItem = children
        }
      }
    }
  }
  if (!cItem) {
    return false
  }
  return cItem.path + '?fid=' + item.id
}

/**
 * 获取系统提交表单信息列表页编辑地址
 * @param {*} item
 */
export const getSysFormListPathByItem = item => {
  let cItem = null
  for (let i in Menu) {
    let menu = Menu[i]
    if (menu.children && menu.children.length > 0) {
      for (let i in menu.children) {
        let children = menu.children[i]
        if (children.id === 'UserSysFormInfo') {
          cItem = children
        }
      }
    }
  }
  if (!cItem) {
    return false
  }
  return cItem.path + '?fid=' + item.id
}

/**
 * 获取系统内容页面编辑地址
 * @param {*} item
 */
export const getSystemItemPathBySystem = item => {
  let children
  if (item.systemType.id === 1 || item.systemType.id === 2) {
    children = getChildrenById('UserSystemArticleItem')
    if (!children) {
      return false
    }
  } else if (item.systemType.id === 3 || item.systemType.id === 4) {
    children = getChildrenById('UserSystemProductItem')
    if (!children) {
      return false
    }
  } else if (item.systemType.id === 5) {
    children = getChildrenById('UserSystemDownloadItem')
    if (!children) {
      return false
    }
  } else if (item.systemType.id === 6) {
    children = getChildrenById('UserSystemFaqItem')
    if (!children) {
      return false
    }
  } else if (item.systemType.id === 7) {
    children = getChildrenById('UserSystemInformationItem')
    if (!children) {
      return false
    }
  } else if (item.systemType.id === 8) {
    children = getChildrenById('UserSystemPdtableItem')
    if (!children) {
      return false
    }
  }
  if (!children) {
    return false
  }
  return children.path + '?sid=' + item.id + '&id=0'
}

export const getSystemItemPathBySystemAimId = (system, aimId) => {
  let children
  if (system.systemType.id === 1 || system.systemType.id === 2) {
    children = getChildrenById('UserSystemArticleItem')
    if (!children) {
      return false
    }
  } else if (system.systemType.id === 3 || system.systemType.id === 4) {
    children = getChildrenById('UserSystemProductItem')
    if (!children) {
      return false
    }
  } else if (system.systemType.id === 5) {
    children = getChildrenById('UserSystemDownloadItem')
    if (!children) {
      return false
    }
  } else if (system.systemType.id === 6) {
    children = getChildrenById('UserSystemFaqItem')
    if (!children) {
      return false
    }
  } else if (system.systemType.id === 7) {
    children = getChildrenById('UserSystemInformationItem')
    if (!children) {
      return false
    }
  } else if (system.systemType.id === 8) {
    children = getChildrenById('UserSystemPdtableItem')
    if (!children) {
      return false
    }
  }
  if (!children) {
    return false
  }
  return children.path + '?sid=' + system.id + '&id=' + aimId
}

export const getSystemItemPathBySystemRepertoryId = (system, hRepertoryId) => {
  let children
  if (system.systemType.id === 1 || system.systemType.id === 2) {
    children = getChildrenById('UserSystemArticleItem')
    if (!children) {
      return false
    }
  }
  if (!children) {
    return false
  }
  return children.path + '?sid=' + system.id + '&id=0&hrepertoryId=' + hRepertoryId
}

/**
 * 通过 param.path 在 list 中找到对应的 item ，修改item的name
 * 在item的name前面拼接 param.prependName
 * 最后返回新的list
 * @param {*} param
 * @param {*} list
 */
export const prependNameByPath = (param, list) => {
  let result = []
  for (let i in list) {
    let item = list[i]
    if (item.path === param.path && item.name.indexOf(param.prependName) !== 0) {
      item.name = param.prependName + item.name
    }
    result.push(item)
  }
  return JSON.parse(JSON.stringify(result))
}

/**
 * 通过 资源库中的以下数据获取资源库的图片资源显示
 * @param {*} hostId
 * @param {*} repertoryId
 * @param {*} suffix
 * @param {*} type
 */
export const getRepertoryImageSrc = obj => {
  let { hostId, repertoryId, suffix, type, link } = obj
  if (type === 0) {
    return getRepertoryImageSrcByHostRepertoryId(hostId, repertoryId, suffix)
    // return getRepertoryImageSrcByHostRepertoryId(hostId, repertoryId, suffix) + '?' + new Date().getTime()
  } else if (type === 4) {
    return link
  }
  // :src="require('@/assets/images/icon_suffix/'+download.file.suffix+'.png')"
  return require('@/assets/images/icon_suffix/' + suffix.toLocaleLowerCase() + '.png')
}

/**
 * 通过 资源库中的数据获取资源库的视频播放地址
 * @param {*} obj
 * @returns
 */
export const getRepertoryVideoSrc = obj => {
  let { hostId, repertoryId, suffix } = obj
  return getRepertoryVideoSrcByHostRepertoryId(hostId, repertoryId, suffix)
}

/**
 * 通过 资源库数据，生成图片地址
 * @param {*} obj
 * @returns
 */
export const getRepertoryImageSrcByHostRepertory = obj => {
  let param = { hostId: obj.hostId, repertoryId: obj.id, suffix: obj.suffix, type: obj.type, link: obj.link }
  return getRepertoryImageSrc(param)
}

/**
 * 通过 资源库数据，生成视频播放地址
 * @param {*} obj
 * @returns
 */
export const getRepertoryVideoSrcByHostRepertory = obj => {
  let param = { hostId: obj.hostId, repertoryId: obj.id, suffix: obj.suffix }
  return getRepertoryVideoSrc(param)
}

/**
 * 下载地址获取
 * @param {*} hostId
 * @param {*} id
 * @param {*} suffix
 */
export const getRepertoryDownloadHref = (hostId, repertoryId, suffix) => {
  return '/api/download/repertory/' + crypto.en('' + hostId) + '/' + crypto.en('' + repertoryId) + '.' + suffix + '?' + Session.routerQueryString() + '&t=' + new Date().getTime()
}

// =========================================不对外开放的部分函数=========================================

/**
 * 通过 hostId 以及 repertoryId 获取相应的图片路径
 * @param {*} hostId
 * @param {*} repertoryId
 */
const getRepertoryImageSrcByHostRepertoryId = (hostId, repertoryId, suffix) => {
  return '/api/image/repertory/' + crypto.en('' + hostId) + '/' + crypto.en('' + repertoryId) + '.' + suffix + '?' + Session.routerQueryString()
}

/**
 * 通过 hostId 以及 repertoryId 获取相应的视频路径
 * @param {*} hostId
 * @param {*} repertoryId
 * @param {*} suffix
 * @returns
 */
const getRepertoryVideoSrcByHostRepertoryId = (hostId, repertoryId, suffix) => {
  return '/api/video/repertory/' + crypto.en('' + hostId) + '/' + crypto.en('' + repertoryId) + '.' + suffix + '?' + Session.routerQueryString()
}

// =========================================公用路由方法=========================================
export const sessionRouter = (path, session) => {
  return {
    path: path,
    query: {
      tk: session
    }
  }
}
/**
 * 获取backendjs窗口定义的方法集合
 * @returns
 */
export const backendjsFunctions = () => {
  if (!store.state.design.ref) {
    console.error('iframe 不存在')
    return false
  }
  var contentWindow = store.state.design.ref.contentWindow
  if (!contentWindow.backendjsFunctions) {
    throw new Error('iframe 不存在 backendjsFunctions 对象')
  }
  return contentWindow.backendjsFunctions
}

/**
 * 去登录页面
 */
export const gotoLoginUrl = () => {
  let sessionloginUrl = sessionStorage.getItem('sessionloginUrl')
  if (store.state.loginUrl) {
    window.location.href = store.state.loginUrl
  } else if (sessionloginUrl) {
    window.location.href = sessionloginUrl
  } else {
    window.location.href = Global.masterUrl
  }
}

/**
 * 是否存在需要发布的数据，如果不存在返回 false
 * @param {*} dataBody 提交到后台的数据
 */
export const publishdata = (dataBody) => {
  if (!dataBody || dataBody === 'nopage') {
    return false
  }
  let jsonBody = JSON.parse(dataBody)
  if (!jsonBody || !jsonBody.operateLog) {
    return false
  }
  return jsonBody.operateLog.length > 0
}

export const modulesIframeSrc = (nus) => {
  let query = qs.stringify({
    nus: nus.join(','),
    theme: store.state.site.config.theme, // 主题号 默认 1
    color: store.state.site.config.color,
    time: new Date().getTime()
  })
  let iframeSrc = '/api/udin/module/official.html?' + query
  return iframeSrc
}

// 获取站点增值配置的方法
var hostSetupResponse = null
export const hostSetup = () => {
  return new Promise((resolve, reject) => {
    try {
      if (hostSetupResponse) {
        resolve(hostSetupResponse)
      } else {
        Vue.prototype.$post('/host/get-current-host-setup', null).then(response => {
          hostSetupResponse = response
          resolve(hostSetupResponse)
        })
      }
    } catch (error) {
      reject(error)
    }
  })
}

export const routerPush = (param) => {
  if (typeof param === 'string') {
    let query = Object.assign({}, Session.routerQuery())
    let router = { path: param, query: query }
    return router
  } else if (typeof param === 'object') {
    let query = Object.assign({}, param.query, Session.routerQuery())
    let router = { path: param.path, query: query }
    return router
  }
}

// 获取站点代理商信息
var agentInfoResponse = null
export const agentInfo = () => {
  return new Promise((resolve, reject) => {
    try {
      if (agentInfoResponse) {
        resolve(agentInfoResponse)
      } else {
        Vue.prototype.$post('/agent/info', null).then(response => {
          agentInfoResponse = response
          resolve(agentInfoResponse)
        })
      }
    } catch (error) {
      reject(error)
    }
  })
}
